//
//  ReHotCViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "ReHotCViewController.h"
#import "HotTableViewCell.h"
#import "FLSFirstHotListModel.h"
#import "RecommondDetialViewController.h"
#import "XiAndShouViewController.h"
#import "SDCycleScrollView.h"
#import "AmbitusListViewController.h"

@interface ReHotCViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, SDCycleScrollViewDelegate>

// 主页tableView
@property (nonatomic, strong) UITableView *recomTableView;
// 接收网址
@property (nonatomic, strong) NSString *url;
// 接收城市景点列表
@property (nonatomic, strong) NSMutableArray *dataArray;
// 轮播图
@property (nonatomic, strong) NSMutableArray *photoArray;
@property (nonatomic, strong) NSMutableArray *seaArray;
// 表头
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) DDIndicator *indicator;

@property (nonatomic, strong) UIView *viewV;

@property (nonatomic, strong) AppDelegate *app;
@property (nonatomic, assign) BOOL isAnimation;


@end

@implementation ReHotCViewController

- (void)dealloc
{
    // 销毁这条通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NOTIFICATIONONEHOTCITY" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    [self.navigationController.navigationBar setTranslucent:YES];
   // self.view.backgroundColor = [UIColor brownColor];
    // Do any additional setup after loading the view.
   
    [self addAnimation];
   [self addSubViews];
    [self freshHeader];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    

    // 注册一条通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hotCityNOT:) name:@"NOTIFICATIONONEHOTCITY" object:nil];
    [self addInternetObserver];
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}


- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
    self.recomTableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpData)];
    [self.recomTableView.header beginRefreshing];
    } else {
        [self.recomTableView.header endRefreshing];
        [self alertController];
    }
}

// 解析数据
- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
        
    
    // 首次加载 默认是北京
    if (self.url == nil) {
        self.url = @"http://app.xialv.com/index2.php?a=sList2&page=1&city_id=1001&type=2";
    }
    // 利用网址字符串创建一个网址对象
    NSURL *url = [NSURL URLWithString:self.url];
    
    // 利用网址对象创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    
    // 设置请求类型
    [request setHTTPMethod:@"GET"];
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    __block ReHotCViewController  *mySelf = self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            return ;
        }
         NSMutableDictionary *datDic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
 
        NSArray *allArray = datDic[@"result"];
        mySelf.dataArray = [NSMutableArray array];
        for (NSDictionary *dic in allArray) {
            FLSFirstHotListModel *model = [[FLSFirstHotListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [mySelf.dataArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopLoading];
            [self.recomTableView.header endRefreshing];
            [mySelf.recomTableView reloadData];
        });
       
        
    }];
    } else {
         [self stopLoading];
         [self.recomTableView.header endRefreshing];
        [self alertController];
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 加载动画
- (void)addAnimation
{
    if (!self.isAnimation) {
        self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake((kScreenWidth - 40) / 2, (kScreenHeight - 40) / 2 , 40, 40)];
        [self.view addSubview:self.indicator];
        [self.indicator startAnimating];
    }
    self.isAnimation = YES;
}

- (void)stopLoading
{
    self.isAnimation = NO;  
    [_indicator stopAnimating];
  
}


// NSNotificationCenter实现接收通知的方法
- (void)hotCityNOT:(NSNotification *)notification
{
    if ([notification.name isEqualToString:@"NOTIFICATIONONEHOTCITY"]) {
        // 接收通知的参数
        NSDictionary *dic = notification.userInfo;
     
        self.url = dic[@"cityUrl"];
        [self setUpData];
    }
}

// 添加视图
- (void)addSubViews
{
    // tableView
    self.recomTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 104) style:(UITableViewStylePlain)];
    self.recomTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 代理
    self.recomTableView.dataSource = self;
    self.recomTableView.delegate = self;
    [self.view addSubview:self.recomTableView];
    //*******************头部轮播图
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth / 2 + 180)];
    NSArray *arr = [self imagesWithTop];
    NSMutableArray *photoArr = [NSMutableArray array];
    NSMutableArray *nameArr = [NSMutableArray array];
//    for (NSDictionary *dic in arr) {
//        NSString *photo = dic[@"photo"];
//        UIImage *image = [UIImage imageNamed:photo];
//        NSString *name = dic[@"name"];
//        [photoArr addObject:image];
//        [nameArr addObject:name];
//    }
    for (int i = 3; i < arr.count; i++) {
        NSDictionary *dic = arr[i];
        NSString *photo = dic[@"photo"];
        UIImage *image = [UIImage imageNamed:photo];
        NSString *name = dic[@"name"];
        [photoArr addObject:image];
        [nameArr addObject:name];
    }
    SDCycleScrollView *scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 180) imagesGroup:photoArr];
    [self.headerView addSubview:scrollView];
    // 字体数组
    scrollView.titlesGroup = nameArr;
    // 背景高度
    scrollView.titleLabelHeight = 25;
    // 字体大小  颜色
    scrollView.titleLabelTextFont = [UIFont systemFontOfSize:16];
    scrollView.titleLabelTextColor = [UIColor whiteColor];
    // 几秒钟换图片
    scrollView.autoScrollTimeInterval = 2.5;
    
    // 小圆点的颜色
    scrollView.dotColor = [UIColor cyanColor];
    
    // 小圆点的位置在中间还是右边
    scrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    // 设置代理
    scrollView.delegate = self;
    //***************轮播图结束
    //###############分类button
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 4; j++) {
            NSInteger m = i * 4 + j;
            if (m < 8) {
                ReKindCityView *kindCity = [[ReKindCityView alloc] initWithFrame:CGRectMake(kScreenWidth / 4 * j, i * kScreenWidth / 4 + 180, kScreenWidth / 4, kScreenWidth / 4)];
                
                kindCity.imageV.image = [UIImage imageNamed:arr[m][@"img"]];
                kindCity.label.text = arr[m][@"name"];
                kindCity.tag = 10 + m;
                [self.headerView addSubview:kindCity];
            }
        }
        
    }
     self.recomTableView.tableHeaderView = self.headerView;
    _bjBT = (ReKindCityView *)[self.view viewWithTag:13];
    [_bjBT.button addTarget:self action:@selector(actionbjBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _shBT = (ReKindCityView *)[self.view viewWithTag:14];
    [_shBT.button addTarget:self action:@selector(actionshBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _gzBT = (ReKindCityView *)[self.view viewWithTag:15];
    [_gzBT.button addTarget:self action:@selector(actiongzBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _szBT = (ReKindCityView *)[self.view viewWithTag:16];
    [_szBT.button addTarget:self action:@selector(actionszBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _xmBT = (ReKindCityView *)[self.view viewWithTag:17];
    [_xmBT.button addTarget:self action:@selector(actionxmBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _seBT = (ReKindCityView *)[self.view viewWithTag:10];
    [_seBT.button addTarget:self action:@selector(actionseBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _xnBT = (ReKindCityView *)[self.view viewWithTag:11];
    [_xnBT.button addTarget:self action:@selector(actionxnBT:) forControlEvents:(UIControlEventTouchUpInside)];
    _zbBT = (ReKindCityView *)[self.view viewWithTag:12];
    [_zbBT.button addTarget:self action:@selector(actionzbBT:) forControlEvents:(UIControlEventTouchUpInside)];
    
   
}

#pragma mark - 滑动的代理方法
// 唯一的代理方法  选中图片执行
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (index < 5) {
        NSString *str1 = self.photoArray[index + 3][@"up"];
        NSString *str2 = self.seaArray[index];
        // 发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEHOTCITY" object:self userInfo:@{@"cityUrl":str1}];
        // 发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEFUNSEASON" object:self userInfo:@{@"funSeason":str2}];
    }

   
    
}

- (NSArray *)imagesWithTop
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"HotCityList" ofType:@"plist"];
    NSArray *plistArray = [NSArray arrayWithContentsOfFile:path];
    self.photoArray = [NSMutableArray array];
    self.seaArray = [NSMutableArray array];
    for (int i = 0; i < 8; i++) {
        NSDictionary *dic = plistArray[i];
        NSString *url = dic[@"photo"];
        NSString *city = dic[@"cityName"];
        NSString *image = dic[@"icon"];
        NSString *list = dic[@"url"];
        NSDictionary *dict = @{@"photo":url, @"name":city, @"img":image, @"up":list};
        [self.photoArray addObject:dict];
        if (i > 2) {
            NSString *season = dic[@"seasonUrl"];
            [self.seaArray addObject:season];
        }
    }
    return self.photoArray;
}

#pragma mark -- UITableViewDataSource协议
// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

// cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"hotCell";
    HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HotTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.dataArray.count > 0) {
        FLSFirstHotListModel *model = self.dataArray[indexPath.row];
        [cell.coverPhoto sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.titleLB.text = model.title;
        
    }
    return cell;
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 215;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *cityname = [[NSString alloc] init];
    for (NSDictionary *dic in self.photoArray) {
        if ([self.url isEqualToString:dic[@"up"]]) {
            cityname = dic[@"name"];
        }
    }
    NSString *str = [NSString stringWithFormat:@" 👣推荐热区                                     %@", cityname];
    return str;
}

// 跳转界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RecommondDetialViewController *detailVC = [[RecommondDetialViewController alloc] init];
    FLSFirstHotListModel *model = self.dataArray[indexPath.row];
    detailVC.headModel = model;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark -- 中间分城
- (void)actionbjBT:(UIButton *)button
{
        [self addAnimation];
    NSString *str1 = self.photoArray[3][@"up"];
    NSString *str2 = self.seaArray[0];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEHOTCITY" object:self userInfo:@{@"cityUrl":str1}];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEFUNSEASON" object:self userInfo:@{@"funSeason":str2}];
}
- (void)actionshBT:(UIButton *)button
{
        [self addAnimation];
    NSString *str1 = self.photoArray[4][@"up"];
    NSString *str2 = self.seaArray[1];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEHOTCITY" object:self userInfo:@{@"cityUrl":str1}];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEFUNSEASON" object:self userInfo:@{@"funSeason":str2}];
}
- (void)actiongzBT:(UIButton *)button
{
        [self addAnimation];
    NSString *str1 = self.photoArray[5][@"up"];
    NSString *str2 = self.seaArray[2];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEHOTCITY" object:self userInfo:@{@"cityUrl":str1}];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEFUNSEASON" object:self userInfo:@{@"funSeason":str2}];
}
- (void)actionszBT:(UIButton *)button
{
        [self addAnimation];
    NSString *str1 = self.photoArray[6][@"up"];
    NSString *str2 = self.seaArray[3];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEHOTCITY" object:self userInfo:@{@"cityUrl":str1}];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEFUNSEASON" object:self userInfo:@{@"funSeason":str2}];
}
- (void)actionxmBT:(UIButton *)button
{
    [self addAnimation];

    NSString *str1 = self.photoArray[7][@"up"];
    NSString *str2 = self.seaArray[4];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEHOTCITY" object:self userInfo:@{@"cityUrl":str1}];
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONONEFUNSEASON" object:self userInfo:@{@"funSeason":str2}];
}
- (void)actionseBT:(UIButton *)button
{
 
     NSString *str1 = self.photoArray[0][@"up"];
    XiAndShouViewController *xiVC = [[XiAndShouViewController alloc] init];
    xiVC.detailsUrl = str1;
    
    xiVC.cityName = @"首尔";
    xiVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:xiVC animated:YES];
    
}
- (void)actionxnBT:(UIButton *)button
{
    NSString *str1 = self.photoArray[1][@"up"];
    XiAndShouViewController *xiVC = [[XiAndShouViewController alloc] init];
    xiVC.detailsUrl = str1;
    xiVC.cityName = @"悉尼";
    xiVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:xiVC animated:YES];
}

- (void)actionzbBT:(UIButton *)button
{
    AmbitusListViewController *aVC = [[AmbitusListViewController alloc] init];
    aVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:aVC animated:YES];
}

@end
